package com.yuyou.fn.common.util;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.exception.BusException;
import okhttp3.*;
import org.springframework.cache.annotation.Cacheable;

import java.util.Date;

/**
 * Created by Administrator on 2018/4/13.
 */
public class ConnectTmsUtils {
    public static String externalUsername="yuyou";
    public static String externalPassword="zy_yuyou_20180726";
    public static final MediaType FORM_CONTENT_TYPE
            = MediaType.parse("application/json;charset=utf-8");

    public static String findToken(String url) throws Exception {
        OkHttpClient client=OkHttpClientUtils.getIgnoreSsLClient(30,500);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username" ,externalUsername);
        jsonObject.put("password" ,externalPassword);//DigestUtils.md5Hex("zy_yuyou_1234"));
        jsonObject.put("time",new Date().getTime());
        RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, jsonObject.toJSONString());
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        if (response.code()!=200){
            throw new BusException("查询TmsToken失败:"+response.code());
        }
        String result = response.body().string();
        JSONObject object = JSONObject.parseObject(result);
        String token = object.getString("token");
        return token;
    }

    public static Request getTmsRequest(String url,String json,String token){
        RequestBody body=RequestBody.create(FORM_CONTENT_TYPE, json);
        Request request = new Request.Builder().addHeader("Authorization",token).url(url).post(body).build() ;
        return request;
    }

}
